﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace NB.MGJ.Common.Helper
{
    public class EDS3
    {
        #region DESEnCode DES加密
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="pToEncrypt"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string DESEnCode(string pToEncrypt)
        {
            //pToEncrypt = HttpContext.Current.Server.UrlEncode(pToEncrypt);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);

            string key = DES3Key;
            des.Key = ASCIIEncoding.ASCII.GetBytes(key);
            des.IV = ASCIIEncoding.ASCII.GetBytes(key);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }
        #endregion

        #region DESDeCode DES解密
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="pToDecrypt"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string DESDeCode(string pToDecrypt)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }
            string key = DES3Key;
            des.Key = ASCIIEncoding.ASCII.GetBytes(key);
            des.IV = ASCIIEncoding.ASCII.GetBytes(key);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }
        #endregion

        public static string DES3Key
        {
            get
            {
                string des3key = ConfigurationManager.AppSettings["DES3Key"];
                if (string.IsNullOrEmpty(des3key)) return "max_2014";
                return des3key;
            }
        }


        #region MD5 32位加密
        /// <summary>
        /// MD5 32位加密
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string EncryptStringWithMd5_32(string source)
        {
            string cl = source;
            string pwd = "";
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();//实例化一个md5对像
            // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符
                pwd = pwd + AddBefore(s[i].ToString("x"), 2);
            }
            return pwd;
        }

        #region 在字符前补零，以达到固定长度
        /// <summary>
        /// 在字符前补零，以达到固定长度
        /// </summary>
        /// <param name="source"></param>
        /// <param name="totalLength"></param>
        /// <returns></returns>
        public static string AddBefore(string source, int totalLength)
        {
            string tempStr = "";
            //先生成"0"的字符串
            for (int loop = 0; loop < totalLength; loop++)
            {
                tempStr += "0";
            }
            tempStr += source;

            //再取后面长度为totalLength的字符串
            tempStr = tempStr.Substring(tempStr.Length - totalLength, totalLength);
            return tempStr;
        }
        #endregion
        #endregion


    }
}
